<template>
  <div class="app-container">
    <!-- 顶部搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="100px">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="研发活动名称:" prop="yfHdName">
            <el-input
              v-model="queryParams.yfHdName"
              placeholder="请输入研发活动名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目编号:" prop="xmBh">
            <el-input
              v-model="queryParams.xmBh"
              placeholder="请输入项目编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="知识产权编号:" prop="zscqBh">
            <el-input
              v-model="queryParams.zscqBh"
              placeholder="请输入知识产权编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="RD编号:" prop="rdBh">
            <el-input
              v-model="queryParams.rdBh"
              placeholder="请输入RD编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="所属单位:" prop="ssDw">
            <el-input
              v-model="queryParams.ssDw"
              placeholder="请输入所属单位"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <!--      <el-form-item label="年度" prop="nd">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.nd"-->
      <!--          placeholder="请输入年度"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
    </el-form>

    <!-- 顶部按钮 -->
    <el-form :model="queryParams" size="mini" label-width="170px">
      <el-row :gutter="10" class="mb8" style="display: flex; justify-content: flex-end;margin-bottom: -8px">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['gqgl:rdb:add']"
            :disabled="!YwJhByGqgl || (YwJhByGqgl !== true)"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['gqgl:rdb:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['gqgl:rdb:remove']"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['gqgl:rdb:export']"
          >导出Excel
          </el-button>
        </el-col>
        <el-col :span="1.5" style="margin-left: auto;">
          <el-form-item label="认定计划:" prop="xmZt">
            <vxe-select @change="getList" size="mini" v-model="queryParams.nd" placeholder="请选择认定计划">
              <vxe-option v-for="item in ywJhList" :key="item.nd" :value="item.nd"
                          :label="item.jhLb"></vxe-option>
            </vxe-select>
          </el-form-item>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-form>

    <!-- 表格 -->
    <el-table @row-click="clickRow" ref="table" highlight-current-row
              :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
              height="300" class="fixedTableTwo" v-loading="loading" :data="rdbList"
              @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="序号" align="center" type="index" :index="indexMethod"/>
      <el-table-column show-overflow-tooltip label="年度" align="center" prop="nd"/>
      <el-table-column show-overflow-tooltip label="RD编号" align="center" prop="rdBh">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleButtonClick(scope.row)"
          >
            <el-link type="primary">{{ scope.row.rdBh }}</el-link>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="项目编号" align="center" prop="xmBh" width="150"/>
      <el-table-column show-overflow-tooltip label="产品/服务名称" align="center" prop="cpFwName" width="180"/>
      <el-table-column show-overflow-tooltip label="研发活动名称" align="center" prop="yfHdName" width="150"/>
      <el-table-column show-overflow-tooltip label="开始时间" align="center" prop="ksTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.ksTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="完成时间" align="center" prop="wcTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.wcTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="技术领域" align="center" prop="jsLy" width="150">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gqgl_jsly" :value="scope.row.jsLy"/>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="技术来源" align="center" prop="jsSource" width="150">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gqgl_jssource" :value="scope.row.jsSource"/>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="知识产权编号" align="center" prop="zscqBh" width="150"/>
      <el-table-column show-overflow-tooltip label="研发总预算(万元)" align="center" prop="ydZys" width="150"/>
      <el-table-column show-overflow-tooltip label="近3年总支出" align="center" prop="jsnZzc" width="150"/>
      <el-table-column show-overflow-tooltip label="其中：第一年" align="center" prop="qzDyn" width="150"/>
      <el-table-column show-overflow-tooltip label="其中：第二年" align="center" prop="qzDen" width="150"/>
      <el-table-column show-overflow-tooltip label="其中：第三年" align="center" prop="qzDsn" width="150"/>
      <el-table-column show-overflow-tooltip label="所属单位" align="center" prop="ssDw" width="150"/>
      <el-table-column show-overflow-tooltip label="依托工程项目" align="center" prop="ytGcXm" width="150"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['gqgl:rdb:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['gqgl:rdb:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改RD对话框 -->
    <vxe-modal :title="title" v-model="open" width="70%" showFooter show-zoom resize>
      <el-form ref="formDialog" :model="form" :rules="rules" label-width="140px">
        <el-tabs type="border-card" v-model="activeName">
          <!-- 基本资料 -->
          <el-tab-pane name="jbzl" :lazy=true>
            <span slot="label"><i class="el-icon-date"></i> 基本资料</span>
            <div v-if="activeName === 'jbzl'" style="height: 65vh; overflow-y: auto;">
              <el-card class="box-card" shadow="never">
                <div slot="header" class="clearfix" style="text-align: center;">
                  <span style="font-size: 20px; color: #1890ff">基本资料</span>
                </div>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="RD编号" prop="rdBh">
                      <el-input disabled v-model="form.rdBh" placeholder="待生成..."/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="年度" prop="nd">
                      <el-input disabled type="number" v-model="form.nd" placeholder="请输入年度"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="项目编号" prop="xmBh" @focus="selectRdXm">
                      <el-input v-model="form.xmBh" placeholder="请输入项目编号" @focus="selectRdXm()"
                                :suffix-icon="'el-icon-search'"/>
                    </el-form-item>
                  </el-col>
                  <!--                <el-form-item label="项目申报ID" prop="xmsbId">-->
                  <!--                  <el-input v-model="form.xmsbId" placeholder="请输入项目申报ID"/>-->
                  <!--                </el-form-item>-->
                  <el-col :span="12">
                    <el-form-item label="研发活动名称" prop="yfHdName">
                      <el-input v-model="form.yfHdName" placeholder="请输入研发活动名称"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="开始时间" prop="ksTime">
                      <el-date-picker clearable style="width: 100%;"
                                      v-model="form.ksTime"
                                      type="date"
                                      value-format="yyyy-MM-dd"
                                      placeholder="请选择开始时间">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="完成时间" prop="wcTime">
                      <el-date-picker clearable style="width: 100%;"
                                      v-model="form.wcTime"
                                      type="date"
                                      value-format="yyyy-MM-dd"
                                      placeholder="请选择完成时间">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="技术领域" prop="jsLy">
                      <el-select v-model="form.jsLy" placeholder="请选择技术领域">
                        <el-option
                          v-for="dict in dict.type.gqgl_jsly"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="技术来源" prop="jsSource">
                      <el-select v-model="form.jsSource" placeholder="请选择技术来源">
                        <el-option
                          v-for="dict in dict.type.gqgl_jssource"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="产品/服务名称" prop="cpFwName">
                      <!--                      <el-input v-model="form.cpFwName" placeholder="请输入产品/服务名称"/>-->
                      <el-select filterable v-model="form.cpFwName" placeholder="请选择产品/服务名称"
                                 style="width: 100%">
                        <el-option
                          @click.native="insPSbId(item)"
                          v-for="item in cpFwList"
                          :key="item.psbId"
                          :label="item.cpfwName"
                          :value="item.cpfwName">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <!--                <el-form-item label="PS表ID" prop="psbId">-->
                  <!--                  <el-input v-model="form.psbId" placeholder="请输入PS表ID"/>-->
                  <!--                </el-form-item>-->
                  <el-col :span="12">
                    <el-form-item label="知识产权编号" prop="zscqBh" @focus="selectIPb">
                      <el-input v-model="form.zscqBh" placeholder="请输入知识产权编号" @focus="selectIPb"
                                :suffix-icon="'el-icon-search'"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <!--                <el-form-item label="IP表ID" prop="ipbId">-->
                <!--                  <el-input v-model="form.ipbId" placeholder="请输入IP表ID"/>-->
                <!--                </el-form-item>-->
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="所属单位" prop="ssDw">
                      <el-input v-model="form.ssDw" placeholder="请输入所属单位"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="依托工程项目" prop="ytGcXm">
                      <el-input v-model="form.ytGcXm" placeholder="请输入依托工程项目"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="研发总预算" prop="ydZys">
                      <el-input v-model="form.ydZys" placeholder="请输入研发总预算"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="近3年总支出" prop="jsnZzc">
                      <el-input v-model="form.jsnZzc" placeholder="请输入近3年总支出"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="其中：第一年" prop="qzDyn">
                      <el-input v-model="form.qzDyn" placeholder="请输入其中：第一年"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="其中：第二年" prop="qzDen">
                      <el-input v-model="form.qzDen" placeholder="请输入其中：第二年"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="其中：第三年" prop="qzDsn">
                      <el-input v-model="form.qzDsn" placeholder="请输入其中：第三年"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="目的及组织实施方式">
                  <el-button @click="getAi(form.yfHdName)">优化</el-button>
                  <editor v-model="form.mdjZzSsFs" :height="192"/>
                </el-form-item>
                <el-form-item label="核心技术及创新点">
                  <editor v-model="form.hxjsJCxd" :height="192"/>
                </el-form-item>
                <el-form-item label="取得的阶段性成果">
                  <editor v-model="form.qddJdxCg" :height="192"/>
                </el-form-item>
              </el-card>
            </div>
          </el-tab-pane>
          <!-- 附件资料 -->
          <el-tab-pane name="fjzl" :lazy=true>
            <span slot="label"><i class="el-icon-date"></i> 附件资料</span>
            <div v-if="activeName === 'fjzl'" style="height: 65vh; overflow-y: auto;">
              <el-card class="box-card" shadow="never">
                <div slot="header" class="clearfix" style="text-align: center;">
                  <span style="font-size: 20px; color: #1890ff">附件资料</span>
                </div>
                <el-row :gutter="20">
                  <el-col :span="7" :xs="24">
                    <div class="head-container">
                      <el-tree
                        :data="fileOptions"
                        :props="defaultProps"
                        :expand-on-click-node="false"
                        :filter-node-method="filterNode"
                        ref="tree"
                        node-key="id"
                        default-expand-all
                        highlight-current
                        @node-click="handleNodeClick"
                        :render-content="renderContent"
                      />
                    </div>
                  </el-col>
                  <el-col :span="17" :xs="24">
                    <el-row :gutter="10" class="mb8">
                      <el-col :span="1.5">
                        <!-- 上传按钮 -->
                        <el-button size="mini" icon="el-icon-upload" type="primary" @click="RDbFileUpload">上传
                        </el-button>
                      </el-col>
                      <el-col :span="1.5">
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteRdbFj">删除
                        </el-button>
                      </el-col>
                    </el-row>
                    <el-table :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                              :data="rdbFjList" :row-class-name="rowRdbFjIndex"
                              @selection-change="handleRdbFjSelectionChange"
                              ref="rdbFj" v-loading="loadingFj">
                      <el-table-column type="selection" width="50" align="center"/>
                      <el-table-column label="序号" align="center" prop="index" width="50"/>
                      <el-table-column label="文件类型" align="center" prop="fileType"/>
                      <el-table-column label="文件名称" align="center" prop="fileName" :formatter="getFileNames"/>
                      <el-table-column label="文件大小" align="center" prop="fileSize"/>
                      <el-table-column width="120" align="center" label="操作" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                          <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleDownload(scope.row)"
                          >下载
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                </el-row>
              </el-card>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

      <!-- 高企认定项目单选 -->
      <GqRdXmDx ref="gqRdXmDx"/>

      <!-- IP表多选编号 -->
      <IPbDuoxBh ref="ipbDuoxBh"/>

      <!-- RD表附件上传弹窗 -->
      <vxe-modal title="附件上传" v-model="fjUpload" width="25%" showFooter show-zoom resize @close="fjClose">
        <el-upload
          align="center"
          class="upload-demo"
          multiple
          :action="uploadFileUrl"
          :before-upload="handleBeforeUpload"
          :file-list="fileList"
          :limit="20"
          :on-error="handleUploadError"
          :on-exceed="handleExceed"
          :on-success="handleUploadSuccess"
          :headers="headers"
          ref="fileUpload"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            请上传
            <template> 大小不超过 <b style="color: #f56c6c">{{ 50 }}MB</b></template>
            <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
            的文件
          </div>
        </el-upload>

        <div slot="footer" class="dialog-footer" style="display: flex; justify-content: center;">
          <el-button v-if="allFilesUploaded === false" size="mini" type="primary" @click="fjUpload = false">关 闭
          </el-button>
          <el-button v-if="allFilesUploaded === true" size="mini" type="primary" @click="fjClose">上传完成, 关闭
          </el-button>
        </div>

      </vxe-modal>
    </vxe-modal>

    <!-- RD表详情组件 -->
    <RdbXq ref="rdbXq"/>
  </div>
</template>

<script>
import {
  addRdb,
  deleteRdbFjByFjIds,
  delRdb,
  getAIToRd,
  getRdb,
  getRDbId,
  insertRdbFjByRdbId,
  listRdb,
  selectRdbFjList,
  updateRdb
} from "@/api/gqgl/rdb";
import {selectYwJh} from "@/api/xtgl/ywjh";
import GqRdXmDx from "@/views/components/GqRdXmXz/GqRdXmDx.vue";
import {selectPSbByRdNd} from "@/api/gqgl/psb";
import IPbDuoxBh from "@/views/components/IPbXz/IPbDuoxBh.vue";
import {getToken} from "@/utils/auth";
import RdbXq from "@/views/gqgl/rdb/components/RdbXq.vue";

export default {
  name: "Rdb",
  components: {RdbXq, IPbDuoxBh, GqRdXmDx},
  dicts: ['gqgl_jsly', 'gqgl_jssource'],
  provide() {
    return {
      updateGqRdXmLabel: (val) => {

        this.form.xmBh = val.xmBh
        this.form.yfHdName = val.xmName
        this.form.ssDw = val.cdDw
        this.form.ksTime = this.convertToStartDate(val.qTime);
        this.form.wcTime = this.convertToStartDate(val.zTime);
        this.form.ydZys = val.xmZe
        this.form.xmsbId = val.xmsbId
        this.form.qzDyn = (val.dyn / 10000).toFixed(2)
        this.form.qzDen = (val.den / 10000).toFixed(2)
        this.form.qzDsn = (val.dsn / 10000).toFixed(2)
        this.form.jsnZzc = ((val.dyn / 10000) + (val.den / 10000) + (val.dsn / 10000)).toFixed(2)
        this.form.rdjhId = val.rdjhId

        this.$refs['formDialog'].validateField('xmBh');
      },
      updateIPbBhLabel: (val) => {
        this.form.ipbId = val.ipbIdStr
        this.form.zscqBh = val.zscqBhStr
        this.$refs['formDialog'].validateField('zscqBh');
      },

    }
  },
  data() {
    return {
      rdbFileType: "项目立项批文", //默认的附件类型
      fileOptions: [
        { // 附件类型树表
          id: 1,
          label: '1.项目立项批文',
          type: '项目立项批文'
        }, {
          id: 2,
          label: '2.研究开发项目任务计划书',
          type: '研究开发项目任务计划书',
          children: [{
            id: 2.1,
            label: '2.合同变更',
            type: '合同变更',
          }]
        }, {
          id: 3,
          label: '3.项目成果简介或研究成果技术报告',
          type: '项目成果简介或研究成果技术报告'
        }, {
          id: 4,
          label: '4.科技成果鉴定证书(已结题项目提供)',
          type: '科技成果鉴定证书(已结题项目提供)'
        }, {
          id: 5,
          label: '5.查新报告(有技术查新报告的项目提供)',
          type: '查新报告(有技术查新报告的项目提供)'
        }, {
          id: 6,
          label: '6.应用证明',
          type: '应用证明'
        }, {
          id: 7,
          label: '7.经济效益证明',
          type: '经济效益证明'
        }, {
          id: 8,
          label: '8.项目取得的成果(包括专利、工法、科技奖)等',
          type: '项目取得的成果(包括专利、工法、科技奖)等'
        },
      ],
      defaultProps: {children: "children", label: "label"}, // 表单参数
      xg: false, //判断是新增还是修改 (false新增 true修改)
      allFilesUploaded: false, // 添加这个来追踪所有文件是否上传完成
      fjUpload: false, //附件上传弹窗
      //要修改的 RD表id
      rdbIdEdit: "",
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      fileList: [],
      headers: {Authorization: "Bearer " + getToken()},
      number: 0,
      uploadList: [],
      fileType: ["doc", "xls", "ppt", "txt", "pdf", "docx", "zip"],
      cpFwList: [], //根据认定年度查询到的产品/服务名称
      getRDbId: null, //从后端获取到的RD表主键ID
      selectedRow: null, // 保存当前选中的行
      YwJhByGqgl: false,
      ywJhList: null, //业务计划列表
      activeName: 'jbzl', //初始打开的标签页
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedRdbFj: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // RD表格数据
      rdbList: [],
      // RB附件表格数据
      rdbFjList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        rdBh: null,
        nd: null,
        xmBh: null,
        xmsbId: null,
        yfHdName: null,
        psbId: null,
        zscqBh: null,
        ipbId: null,
        ssDw: null,
        idWhere: null,
        userId: null,
        deptId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        nd: [{required: true, message: "年度不能为空", trigger: "blur"}],
        xmBh: [{required: true, message: "项目编号不能为空", trigger: "blur"}],
        yfHdName: [{required: true, message: "研发活动名称不能为空", trigger: "blur"}],
        jsLy: [{required: true, message: "技术领域不能为空", trigger: "change"}],
        jsSource: [{required: true, message: "技术来源不能为空", trigger: "change"}],
        cpFwName: [{required: true, message: "产品/服务名称不能为空", trigger: "blur"}],
      },
      loadingFj: false,
    };
  },
  created() {
    this.getListS();
  },
  watch: {
    activeName(newVal) {
      if (newVal === 'fjzl') {
        this.clickFirstNode();
      }
    },
  },
  mounted() {
    if (this.activeName === 'fjzl') {
      this.clickFirstNode();
    }
  },
  methods: {
    // 查询RD表详情信息
    handleButtonClick(row) {
      this.$refs.rdbXq.handleOpen(row);
    },
    clickFirstNode() {
      this.$nextTick(() => {
        const firstNode = this.$refs.tree.store.nodesMap['1']; // 默认点击id为1的节点
        if (firstNode) {
          this.$refs.tree.setCurrentKey(firstNode.key);
          this.handleNodeClicks(firstNode.data);
        }
      });
    },
    handleNodeClicks(data) {
      this.loadingFj = true
      let rdbId = null
      if (this.xg === false) {
        rdbId = this.getRDbId
      } else {
        rdbId = this.rdbIdEdit
      }
      this.rdbFileType = data.type
      selectRdbFjList(rdbId, this.rdbFileType).then(resFileList => {
        this.rdbFjList = resFileList.data;
        this.loadingFj = false
      })
    },
    // 节点单击事件
    handleNodeClick(data, node) {
      this.loadingFj = true
      let rdbId = null
      if (this.xg === false) {
        rdbId = this.getRDbId
      } else {
        rdbId = this.rdbIdEdit
      }
      //根据附件类型查询附件列表
      this.rdbFileType = data.type
      selectRdbFjList(rdbId, this.rdbFileType).then(resFileList => {
        this.rdbFjList = resFileList.data;
        this.loadingFj = false
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 文件下载处理
    handleDownload(row) {
      const resource = row.fileName;
      // 默认方法
      this.$download.resource(resource);
    },
    // 获取文件名原名
    getFileNames(row) {
      // 从路径中提取文件名
      return row.fileName.split('/').pop(); // 返回文件名部分
    },
    //关闭上传附件弹窗后
    fjClose() {
      this.fileList = []
      this.allFilesUploaded = false
      this.fjUpload = false
    },
    //上传文件之前的钩子
    handleBeforeUpload(file) {
      let that = this;
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        this.$modal.loading("正在上传文件，请稍候...");
        this.number++;
        return true;
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs !== '' ? strs.substr(0, strs.length - 1) : '';
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传成功
    handleUploadSuccess(res, file) {
      let that = this;
      if (res.code === 200) {
        this.uploadList.push({name: res.fileName, url: res.fileName, size: that.formatFileSize(file.size)});
        let xzItemFile = {
          "rdbId": that.getRDbId,
          "fileType": this.rdbFileType,
          "fileName": res.fileName,
          "fileSize": that.formatFileSize(file.size)
        };
        let xgItemFile = {
          "rdbId": that.rdbIdEdit,
          "fileType": this.rdbFileType,
          "fileName": res.fileName,
          "fileSize": that.formatFileSize(file.size)
        };
        if (this.xg === false) {
          // 点击新增按钮的上传
          insertRdbFjByRdbId(xzItemFile).then(resFil => {
            that.getRdbFjList();
          })
        } else if (this.xg === true) {
          // 点击修改按钮的上传
          insertRdbFjByRdbId(xgItemFile).then(resFil => {
            that.getRdbFjList();
          })
        }
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
      this.allFilesUploaded = true
      this.$modal.msgSuccess("上传成功")
      // this.fjShangChuan = false
    },
    getRdbFjList() {
      let that = this;
      if (this.xg === false) {
        //点击新增 上传文件后的文件列表
        selectRdbFjList(that.getRDbId, that.rdbFileType).then(resFileList => {
          that.rdbFjList = resFileList.data;
        })
      } else {
        //点击修改 上传文件后的文件列表
        selectRdbFjList(that.rdbIdEdit, that.rdbFileType).then(resFileList => {
          that.rdbFjList = resFileList.data;
        })
      }
    },
    // 显示文件大小为KB, MB, GB, TB
    formatFileSize(size) {
      if (size === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(size) / Math.log(k));
      return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.fileList = this.fileList.map(item => {
          // 使用split方法去除name中的特定前缀
          item.name = item.name.split('/').pop();
          return item;
        });
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },
    //附件上传按钮
    RDbFileUpload() {
      this.fjUpload = true;
    },
    //选择关联IP
    selectIPb() {
      this.$refs.ipbDuoxBh.handleOpen(this.form.ipbId, this.queryParams.nd);
    },
    //根据选择的产品/服务名称 插入对应的psbId
    insPSbId(item) {
      this.form.psbId = item.psbId
    },
    //点击行 获取行
    clickRow(row) {
      this.selectedRow = row; // 更新选中的行
      const table = this.$refs.table;
      const selectedRows = table.selection;

      // 否则取消之前选中的行，并选中当前点击的行
      selectedRows.forEach(selectedRow => {
        table.toggleRowSelection(selectedRow);
      });
      table.toggleRowSelection(row);
    },
    /** 自定义序号 */
    indexMethod(index) {
      let pageNum = this.queryParams.pageNum - 1;
      if ((pageNum !== -1 && pageNum !== 0)) {
        return (index + 1) + (pageNum * this.queryParams.pageSize);
      } else {
        return (index + 1)
      }
    },
    convertToStartDate(yearMonthStr) {
      // 解析输入的年月字符串
      const [year, month] = yearMonthStr.split('-').map((value, index) => {
        return parseInt(index === 0 ? value : value - 1); // 注意：月份需要减1，因为JS中月份从0开始计算
      });

      // 创建并返回对应的Date对象
      return new Date(year, month, 1);
    },
    // 打开选择认定项目弹窗
    selectRdXm() {
      this.$refs.gqRdXmDx.handleOpen(this.queryParams.nd);
    },
    getAi(yfHdName) {
      this.$modal.loading("正在导出数据，请稍后...");
      getAIToRd("帮我优化一下:" + yfHdName + "这个研发活动名称").then(res => {
        alert(res.msg)
        this.$modal.closeLoading();
      })
    },
    //刚开始的查询
    getListS() {
      this.loading = true;
      let query = {
        pageNum: 1,
        pageSize: 50,
        ywSb: '平台资质',
        ywLx: '高企认定',
        zt: '启用'
      }
      selectYwJh(query).then(res => {
        this.ywJhList = res.rows;

        this.queryParams.nd = this.ywJhList[0].nd
        selectPSbByRdNd(this.queryParams.nd).then(res => {
          this.cpFwList = res.data
        })
        listRdb(this.queryParams).then(response => {
          let query = {
            pageNum: 1,
            pageSize: 50,
            nd: this.queryParams.nd,
            ywSb: '平台资质',
            ywLx: '高企认定',
          }
          selectYwJh(query).then(res => {
            let ywjhList = res.rows;
            if (ywjhList[0].jhZt == '进行中') {
              this.YwJhByGqgl = true
            } else {
              this.YwJhByGqgl = false
            }

            this.rdbList = response.rows;
            this.total = response.total;
            this.loading = false;
          });
        });
      });

    },
    /** 查询RD列表 */
    getList() {
      this.loading = true;
      listRdb(this.queryParams).then(response => {
        selectPSbByRdNd(this.queryParams.nd).then(res => {
          this.cpFwList = res.data
        })
        let query = {
          pageNum: 1,
          pageSize: 50,
          nd: this.queryParams.nd,
          ywSb: '平台资质',
          ywLx: '高企认定',
        }
        selectYwJh(query).then(res => {
          let ywjhList = res.rows;
          if (ywjhList[0].jhZt == '进行中') {
            this.YwJhByGqgl = true
          } else {
            this.YwJhByGqgl = false
          }

          this.rdbList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        rdbId: this.getRDbId,
        rdBh: null,
        nd: null,
        xmBh: null,
        xmsbId: null,
        yfHdName: null,
        ksTime: null,
        wcTime: null,
        jsLy: null,
        jsSource: null,
        cpFwName: null,
        psbId: null,
        zscqBh: null,
        ipbId: null,
        ssDw: null,
        ytGcXm: null,
        ydZys: null,
        jsnZzc: null,
        qzDyn: null,
        qzDen: null,
        qzDsn: null,
        mdjZzSsFs: null,
        hxjsJCxd: null,
        qddJdxCg: null,
        idWhere: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        userId: null,
        deptId: null,
        rdjhId: null,
      };
      this.rdbFjList = [];
      this.resetForm("formDialog");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      let ids = selection.map(item => item.rdbId)
      if (ids.length === 1) {
        this.ids = ids[0]
      } else {
        this.ids = ids
      }
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.xg = false
      getRDbId().then(res => {
        this.getRDbId = res.msg
        this.reset();
        this.form.nd = this.queryParams.nd
      })
      this.activeName = 'jbzl'
      this.open = true;
      this.title = "添加RD";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      this.xg = true
      const rdbId = row.rdbId || this.ids
      this.rdbIdEdit = row.rdbId || this.ids
      getRdb(rdbId).then(response => {
        this.form = response.data;

        selectRdbFjList(rdbId, this.rdbFileType).then(resFileList => {
          this.rdbFjList = resFileList.data
        })
        this.activeName = 'jbzl'
        this.open = true;
        this.title = "修改RD";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formDialog"].validate(valid => {
        if (valid) {
          this.form.rdbFjList = this.rdbFjList;
          if (this.form.idWhere != null) {
            updateRdb(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.xg = false
            });
          } else {
            addRdb(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const rdbIds = row.rdbId || this.ids;
      this.$modal.confirm('确定删除选中记录？').then(function () {
        return delRdb(rdbIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** RB附件序号 */
    rowRdbFjIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** RB附件删除按钮操作 */
    handleDeleteRdbFj() {
      if (this.checkedRdbFj.length == 0) {
        this.$modal.msgError("请先选择要删除的RB附件数据");
      } else {
        const fjIds = this.checkedRdbFj;
        this.$modal.confirm('确定删除选中记录？').then(function () {
          return deleteRdbFjByFjIds(fjIds);
        }).then(() => {
          if (this.xg == false) {
            selectRdbFjList(this.getRDbId, this.rdbFileType).then(resFileList => {
              this.rdbFjList = resFileList.data;
            })
          } else {
            selectRdbFjList(this.rdbIdEdit, this.rdbFileType).then(resFileList => {
              this.rdbFjList = resFileList.data;
            })
          }
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      }
    },
    /** 复选框选中数据 */
    handleRdbFjSelectionChange(selection) {
      this.checkedRdbFj = selection.map(item => item.fjId)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('gqgl/rdb/export', {
        ...this.queryParams
      }, `rdb_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>
